/*
	This program is free software; you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation; either version 2 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU Library General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
*/

#include "templatesmodel.h"
#include "constantes.h"

#include <QFile>
#include <QTextStream>
#include <QDomDocument>
#include <QDateTime>
#include <QFileDialog>

TemplateItem::TemplateItem(QString name, QString creationDate, QString data, bool selected)
{
	templateName = name;
	templateCreationDate = creationDate;
	templateData = data;
	templateSelected = selected;
}

TemplateManager::TemplateManager()
{
	templateList = new QList<TemplateItem *>();
	
	readTemplates();
}

TemplateManager::~TemplateManager()
{
	writeTemplates();
	
	TemplateItem *templateItem;
	foreach(templateItem, *templateList)
		delete templateItem;
	
	delete templateList;
}

int TemplateManager::getTemplateCount()
{
	return templateList->count();
}

QString TemplateManager::getTemplateName(int index)
{
	TemplateItem *item = templateList->at(index);
	return item->templateName;
}

QString TemplateManager::getTemplateData(int index)
{
	TemplateItem *item = templateList->at(index);
	return item->templateData;
}

bool TemplateManager::isTemplateSelected(int index)
{
	TemplateItem *item = templateList->at(index);
	return item->templateSelected;
}

QString TemplateManager::getTemplateDataByName(QString name)
{
	QString itemName;
	QString result = NULL;
	
	for (int i = 0; i < templateList->count(); i++)
	{
		itemName = getTemplateName(i);
		if (itemName == name)
		{
			result = getTemplateData(i);
			break;
		}
	}
	return result;
}

void TemplateManager::setTemplateName(int index, QString newName)
{
	TemplateItem *item = templateList->at(index);
	item->templateName = newName;
}

void TemplateManager::setTemplateSelected(int index, bool value)
{
	TemplateItem *item = templateList->at(index);
	item->templateSelected = value;
}

void TemplateManager::readTemplates()
{
	QString filename = Constantes::getConfigPath() + Constantes::TEMPLATES_FILENAME;
	
	QDomDocument doc;
	QFile file(filename);
    if (!file.open(QIODevice::ReadOnly))
        return;
    if (!doc.setContent(&file))
    {
        file.close();
        return;
    }
    
    // File informations
    QFileInfo fileInfo(file);
    QDateTime fileCreationDate = fileInfo.created();
    
    file.close();

    QDomElement root = doc.documentElement();
    QDomElement node = root.toElement();

	int counter = 0;
	QString tagName;
	QString templateName;
	QString templateCreationDate;
	QString templateData;
	bool templateSelected;
	
	TemplateItem *templateItem;
	
	while (!node.isNull())
	{
		QDomElement child = node.firstChildElement();
		while (!child.isNull())
		{
			if (counter > Constantes::NB_MAX_TEMPLATES)
				break;
				
			tagName = child.tagName();
			if (tagName == Constantes::TAG_TEMPLATE)
			{
				templateName = child.attribute(Constantes::TAG_NAME);
				templateCreationDate = child.attribute(Constantes::TAG_DATE);
				if (templateCreationDate.isNull())
					templateCreationDate = fileCreationDate.toString(Constantes::DEFAULT_DATE_FORMAT);
				templateData = child.firstChildElement(Constantes::TAG_DATA).text();
				templateSelected = (child.attribute(Constantes::TAG_SELECTED) == "true") ? true : false;
				
				templateItem = new TemplateItem(templateName, templateCreationDate, templateData, templateSelected);
				templateList->append(templateItem);
			}
			counter++;
			child = child.nextSiblingElement();
		}
		node = node.nextSiblingElement();
	}
}

void TemplateManager::writeTemplates()
{
	QString filename = Constantes::getConfigPath() + Constantes::TEMPLATES_FILENAME;
	
	QDomDocument doc;
	QDomElement element;
    QTextStream out;
	QFile file;
	TemplateItem *templateItem;
	
	// Create the base element "styles".
    QDomElement root = doc.createElement(Constantes::TAG_TEMPLATES);
    doc.appendChild(root);
	
	// Setup the file
    file.setFileName(filename);
    if (!file.open(QIODevice::WriteOnly))
        return;        
    out.setDevice(&file);

	for (int i = 0; i < templateList->count(); i++)
	{
		templateItem = templateList->at(i);
		
		element = doc.createElement(Constantes::TAG_TEMPLATE);
		root.appendChild(element);
		element.setAttribute(Constantes::TAG_NAME, templateItem->templateName);
		element.setAttribute(Constantes::TAG_DATE, templateItem->templateCreationDate);
		element.setAttribute(Constantes::TAG_SELECTED, templateItem->templateSelected ? "true" : "false");
		
		// Add the data node.
		QDomElement dataNode = doc.createElement(Constantes::TAG_DATA);
		element.appendChild(dataNode);
		QDomCDATASection dataText = doc.createCDATASection(templateItem->templateData);
		dataNode.appendChild(dataText);
	}
	
	// Insert <?xml version="1.0" ?> at the begining of the document.
    QDomNode node = doc.createProcessingInstruction("xml","version=\"1.0\"");
    doc.insertBefore(node, doc.firstChild());
    // write the file.
    doc.save(out, 2);
    file.close();
}

void TemplateManager::updateModelFromList(QListWidget *list)
{
	int index;
	TemplateItem *templateItem;
	QList<TemplateItem *> *newList = new QList<TemplateItem *>();
	QListWidgetItem *item;
	
	for (int i = 0; i < list->count(); i++)
	{
		item = list->item(i);
		index = item->data(Qt::UserRole).toUInt();
		templateItem = templateList->at(index);
		newList->append(templateItem);
	}
		
	delete templateList;
	templateList = newList;
}

bool TemplateManager::doTemplateExist(QString name)
{
	bool result = false;
	QString currentName;
	for (int i = 0; i < templateList->count(); i++)
	{
		currentName = getTemplateName(i);
		if (currentName == name)
		{
			result = true;
			break;
		}
	}
	return result;
}

void TemplateManager::addTemplate(QString name, QString data)
{
	TemplateItem *newTemplate = new TemplateItem(name, QDateTime::currentDateTime().toString(Constantes::DEFAULT_DATE_FORMAT), data, true);
	templateList->append(newTemplate);
}
